import java.util.PriorityQueue;
class MyTimer{
    //使用优先级队列来存储要执行任务的顺序
    private PriorityQueue<MyTimerTask> priorityQueue = new PriorityQueue<>();
    //Object locker = new Object();
    public void schedule(Runnable runnable, long delay){
        synchronized (this){//修改操作
            priorityQueue.offer(new MyTimerTask(runnable,delay));
            this.notify();
        }
    }
    //扫描线程，看时间是否到了，执行任务
    public MyTimer(){
        Thread t = new Thread(() -> {
            while(true){
                try{
                    synchronized (this){//修改操作
                        while(priorityQueue.isEmpty()){
                            this.wait();//类似于阻塞队列
                        }
                        MyTimerTask task = priorityQueue.peek();
                        long time = System.currentTimeMillis();//得到当前时间戳
                        if(time >= task.getTime()){
                            task.getRunnable().run();//时间到了，运行任务
                            priorityQueue.poll();
                        }else{
                            this.wait(task.getTime() - time);
                        }
                    }
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
        });
        t.start();
    }
}
class MyTimerTask implements Comparable<MyTimerTask>{
    private Runnable runnable;//要执行的任务
    private long time;//执行任务的时间
    public MyTimerTask(Runnable runnable, long delay){
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + delay;
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int) (this.time - o.time);
    }
    public long getTime(){
        return this.time;
    }
    public Runnable getRunnable(){
        return this.runnable;
    }
}
public class Demo2 {
    public static void main(String[] args) {
        MyTimer myTimer = new MyTimer();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("1000");
            }
        },1000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("2000");
            }
        },2000);
    }
}
